package bill.study.concurrency.lock;

import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class RWDictionary {
	private final Map<String, Data> dictionary = new TreeMap<String, Data>();
	private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
	private final Lock readLock = rwl.readLock();
	private final Lock writeLock = rwl.writeLock();

	public Data get(String key) {
		readLock.lock();
		try {
			return dictionary.get(key);
		} finally {
			readLock.unlock();
		}
	}

	public String[] allKeys() {
		readLock.lock();
		try {
			return dictionary.keySet().toArray(new String[0]);
		} finally {
			readLock.unlock();
		}
	}

	public Data put(String key, Data value) {
		writeLock.lock();
		try {
			return dictionary.put(key, value);
		} finally {
			writeLock.unlock();
		}
	}

	public void clear() {
		writeLock.lock();
		try {
			dictionary.clear();
		} finally {
			writeLock.unlock();
		}
	}
}
